import { calculateDate, getStringDate, error, verifyFormParams } from '../../lib/js/utils'
import { getCostType, getAcceptDatePatCondition } from '../../api/code'
import { BASE_URL } from '../../api/config'
import { sendPublishDate } from '../../api/publishDatePat'
import { IMAGE_SERVER_URL } from '../../api/config'
import { uploadImage } from '../../api/image'
import { getAllOccupation } from '../../api/occupation'

import { isObject } from '../../lib/js/utils'

Page({
  /**
   * 上传图片，可以上传多个
   */
  uploadImages: function (params) {
    const that = this
    wx.chooseMessageFile({
      count: 5,
      type: 'image',
      extension: ['jpg', 'jpeg', 'png', 'bmp', 'wbmp'],
      // sizeType: "original",
      // sourceType: "album",
      success(res) {
        // 进行文件上传
        res.tempFiles.forEach(element => {
          uploadImage(element.path).then(
            function (res) {
              // 使用 wx.uploadFile() 后返回的数据是字符串，不是对象
              // 需要手动调用 JSON.parse()
              // 将返回的 url 添加到 data 中
              res.data.forEach(item => {
                item.url = `${IMAGE_SERVER_URL}/${item.url}`
                that.data.slectedImageUrls.push(item)
                var tempImageUrls = that.data.slectedImageUrls
                that.setData({
                  slectedImageUrls: tempImageUrls
                })
              })
            },
            function (res) {
              error('上传失败')
            }
          )
        })
      }
    })
  },
  /**
   * 提交表单
   * @param {event} e
   */
  doSubmit: function (e) {
    const that = this

    // 获取参数
    var title = e.detail.value.title

    var money = 0
    if (e.detail.value.money) {
      money = e.detail.value.money
    }
    var imageIds = that.data.slectedImageUrls.map(item => {
      return item.id
    })
    var find = that.data.findList[that.data.findIndex].code
    var content = e.detail.value.textarea

    if (!verifyFormParams(title, find, content)) {
      error('标题,约拍对象,约拍要求不能为空哦~~')
    }
    // 发送请求给后端
    sendPublishDate({
      costType: that.data.costType[that.data.costTypeIndex].code,
      datePatCondition: that.data.acceptCondition[that.data.acceptConditionIndex].code,
      datePatDescribe: content,
      imageIds,
      money,
      title,
      occupationId: that.data.findList[that.data.findIndex].id
    }).then(function (res) {
      // 发送成功回调
      console.log(res)
      wx.showToast({
        title: '发布成功！',
      })
    })
  },
  /**
   * 加载业务参数
   */
  initData: function () {
    const that = this
    // 加载约拍职业
    getAllOccupation().then(function (res) {
      that.setData({
        findList: res.data
      })
    })
    // 加载费用类型
    getCostType().then(function (res) {
      that.setData({
        costType: res.data
      })
    })
    // 加载约拍条件
    getAcceptDatePatCondition().then(function (res) {
      that.setData({
        acceptCondition: res.data
      })
    })
  },
  /**
   * 选择约拍对象回调
   * @param {*} e
   */
  changeFind: function (e) {
    var findIndex = e.detail.value
    this.setData({
      findIndex: findIndex
    })
  },
  /**
   * 选择费用类型回调
   * @param {} e
   */
  changeCostType: function (e) {
    var costTypeIndex = e.detail.value
    this.setData({
      costTypeIndex: costTypeIndex
    })
  },
  /**
   * 选择接受约拍对象回调
   * @param {} e
   */
  changeAcceptCondition: function (e) {
    var acceptConditionIndex = e.detail.value
    this.setData({
      acceptConditionIndex: acceptConditionIndex
    })
  },
  /**
   * textarea 点击完成回调
   * @param {*} e
   */
  textareaConfirm: function (e) {
    var text = e.detail.value
    // 检测字符数量
    if (text.length < 10) {
      error('您的要求太低了，再加点吧...')
    }
  },

  /**
   * 设置日期
   * @param {event} e
   */
  dateChange: function (e) {
    this.setData({
      expectedDate: e.detail.value
    })
  },
  /**
   * 页面的初始数据
   */
  data: {
    findList: [],
    findKey: 'occupationName',
    findIndex: 0,
    // 约拍描述要求
    condition: null,
    slectedImageUrls: [],

    // 接受约拍条件（1 接受所有人约拍,2 接受男生约拍，3 接受女生约拍)
    acceptCondition: [],
    acceptConditionIndex: 0,
    // 费用类型
    costType: [],
    costTypeIndex: 1,

    expectedDate: getStringDate(),
    startDate: getStringDate(),
    endDate: getStringDate(calculateDate(365 * 10))
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initData()
  }
})